package com.icesoft.system.file.controller;

import ch.qos.logback.core.util.FileUtil;
import com.icesoft.framework.core.util.PathUtil;
import com.icesoft.framework.core.vo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;

@Slf4j
@RestController
@RequestMapping("")
public class UploadController {

	private static final String UPLOAD_DIR = PathUtil.getRootUploadPath(); // 上传文件保存的目录

	@PostMapping("/file/img/upload")
	public JsonResult<?> upload(@RequestParam("file") MultipartFile file,
								@RequestParam("fileName") String fileName,
								@RequestParam("isPublic") boolean isPublic,
								@RequestParam("md5") String md5) throws IOException {
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		if (md5 == null || md5.length() == 0) {
			return JsonResult.FAIL_VALIDATION("文件名不能为空");
		}
		// 上传的文件保存在一个临时目录中
		String path = UPLOAD_DIR + (isPublic ? "public" : "private") + "/img/" + md5 + suffix;
		File outputFile = new File(path);
		if (!outputFile.exists()) {
			FileUtil.createMissingParentDirectories(outputFile);
		} else {
			return JsonResult.OK("/" + path.replace(PathUtil.getProjectRootPath(), ""));
		}
		try {
			file.transferTo(outputFile);
		} catch (Exception e) {
			log.error("", e);
			// 如果上传失败，返回错误信息
			return JsonResult.FAIL_EXCEPTION("Failed to upload file " + fileName);
		}
		String calculatedMd5 = calculateMd5(outputFile);
		if (!md5.equals(calculatedMd5)) {
			outputFile.delete();
			return JsonResult.FAIL_EXCEPTION("MD5 checksum failed");
		}
		return JsonResult.OK("/" + path.replace(PathUtil.getProjectRootPath(), "") );
	}

	@PostMapping("/file/upload")
	public JsonResult<?> upload(@RequestParam("file") MultipartFile file,
								@RequestParam("chunkNumber") int chunkNumber,
								@RequestParam("totalChunks") int totalChunks,
								@RequestParam("fileName") String fileName,
								@RequestParam("md5") String md5) throws IOException {

		String suffix = fileName.substring(fileName.lastIndexOf("."));
		if (md5 == null || md5.length() == 0) {
			return JsonResult.FAIL_VALIDATION("文件名不能为空");
		}
		// 上传的文件保存在一个临时目录中
		String tempDir = UPLOAD_DIR + "/tmp/";
		File tempFile = new File(tempDir + md5 + ".part" + chunkNumber);
		if (!tempFile.exists()) {
			FileUtil.createMissingParentDirectories(tempFile);
		} else {
			String path = UPLOAD_DIR + md5+ suffix;
			return JsonResult.OK("/" + path.replace(PathUtil.getProjectRootPath(), "") );
		}
		try {
			file.transferTo(tempFile);
		} catch (Exception e) {
			log.error("", e);
			// 如果上传失败，返回错误信息
			return JsonResult.FAIL_EXCEPTION("Failed to upload chunk " + chunkNumber);
		}

		// 如果是最后一个分片，则将所有分片合并成一个文件并进行 MD5 校验
		if (chunkNumber == totalChunks) {
			String path = UPLOAD_DIR + md5+ suffix;
			File outputFile = new File(path);
			FileOutputStream outputStream = new FileOutputStream(outputFile);
			for (int i = 1; i <= totalChunks; i++) {
				File partFile = new File(tempDir + md5 + ".part" + i);
				FileInputStream inputStream = new FileInputStream(partFile);
				byte[] buffer = new byte[1024];
				int len;
				while ((len = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, len);
				}
				inputStream.close();
				partFile.delete();
			}
			outputStream.close();

			// 进行 MD5 校验
			String calculatedMd5 = calculateMd5(outputFile);
			if (!md5.equals(calculatedMd5)) {
				outputFile.delete();
				return JsonResult.FAIL_EXCEPTION("MD5 checksum failed");
			}
			return JsonResult.OK("/" + path.replace(PathUtil.getProjectRootPath(), "") );
		}
		return JsonResult.OK();
	}


	private String calculateMd5(File file) throws IOException {
		FileInputStream inputStream = new FileInputStream(file);
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			byte[] buffer = new byte[1024];
			int len;
			while ((len = inputStream.read(buffer)) != -1) {
				digest.update(buffer, 0, len);
			}
			byte[] md5Bytes = digest.digest();
			return DatatypeConverter.printHexBinary(md5Bytes).toLowerCase();
		} catch (Exception e) {
			log.error("", e);
			throw new RuntimeException("MD5 algorithm not found");
		} finally {
			inputStream.close();
		}
	}

	@GetMapping(value = "/uploadFiles/{isPublic}/img/{filename}")
	public JsonResult preview(@PathVariable String filename, @PathVariable String isPublic, HttpServletResponse response) throws Exception {
		String filePath = "/uploadFiles/" + isPublic + "/img/" + filename;
		File file = PathUtil.getPathFile(filePath.substring(1));
		if (!file.exists()) {
			return null;
		}
		IOUtils.copy(FileUtils.openInputStream(file), response.getOutputStream());
		return null;
	}

	@GetMapping(value = "/uploadFiles/{filename}")
	public JsonResult preview(@PathVariable String filename, HttpServletResponse response) throws Exception {
		String filePath = "/uploadFiles/" + filename;
		File file = PathUtil.getPathFile(filePath.substring(1));
		if (!file.exists()) {
			return null;
		}
		IOUtils.copy(FileUtils.openInputStream(file), response.getOutputStream());
		return null;
	}
}


